<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800px"
    draggable
    :destroy-on-close="true"
    :close-on-press-escape="false"
    @close="closeDialog"
  >
    <CommonForm
      :formConfig="formConfig"
      ref="formRef"
      :inline="true"
      :cols="2"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "PARTNERSRMUSERADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible", "get-enabled-list"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

/**
 * 密码校验
 */
function passwordValidator(rule: any, value: any, callback: any) {
  if (value.length < 6) {
    callback(new Error("长度不少于6位"));
  } else {
    callback();
  }
}
/**
 * 二次密码校验
 */
function checkRepeatPsw(rule: object, value: string, callback: any) {
  if (formRef.value.get("password") === value) {
    callback();
  }
  callback(new Error("密码不一致，请重试"));
}

const checkMobile = (rule: any, value: any, callback: any) => {
  if (value != "") {
    let regx = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (regx.test(value)) {
      callback();
    } else {
      callback(new Error("请输入正确格式电话号"));
    }
  } else {
    callback();
  }
};

/**
 * 密码 config
 */
const passwordFormConfig = [
  {
    type: "input",
    inputType: "text",
    label: "密码",
    fieldName: "password",
    placeholder: "请输入密码",
    initValue: "",
    rules: [
      { required: true, trigger: "blur", validator: passwordValidator },
      { max: 45, message: "不能超过45个字符", trigger: "blur" },
    ],
  },
  {
    type: "input",
    inputType: "text",
    label: "确认密码",
    fieldName: "repeatPassword",
    placeholder: "请输入再次输入密码",
    initValue: "",
    rules: [
      { required: true, trigger: "blur", validator: passwordValidator },
      { required: true, validator: checkRepeatPsw, trigger: "blur" },
      { max: 45, message: "不能超过45个字符", trigger: "blur" },
    ],
  },
];

/**
 * 初始化 config
 */
const createFormConfig = [
  {
    type: "input", // 普通输入框
    inputType: "text", // 类型, text/textarea
    label: "用户姓名", // 标签文本
    fieldName: "firstName", // 字段名称
    placeholder: "请输入用户姓名", // 提示文字
    initValue: "", // 默认值
    rules: [
      { required: true, message: "请输入用户姓名", trigger: "blur" },
      { max: 45, message: "不能超过45个字符", trigger: "blur" },
    ],
  },
  {
    type: "input",
    inputType: "text",
    label: "登录名",
    fieldName: "loginName",
    placeholder: "请输入登录名",
    initValue: "",
    rules: [
      { required: true, message: "请输入登录名", trigger: "blur" },
      { max: 45, message: "不能超过45个字符", trigger: "blur" },
    ],
  },
  {
    type: "select",
    label: "所属供应商",
    fieldName: "partnerId",
    placeholder: "请选择所属供应商",
    initValue: "",
    optionList: [],
    rules: [{ required: true, message: "请选择所属供应商", trigger: "blur" }],
  },
  {
    type: "input",
    inputType: "text",
    label: "手机号",
    fieldName: "mobile",
    placeholder: "请输入手机号",
    initValue: "",
    rules: [{ validator: checkMobile, trigger: "blur" }],
  },
  {
    type: "select",
    label: "性别",
    fieldName: "sexType",
    placeholder: "请选择性别",
    initValue: "",
    optionList: [],
  },
  {
    type: "select",
    label: "是否启用",
    fieldName: "enabled",
    placeholder: "请选择是否启用",
    initValue: "",
    defaultFirstOption: true,
    optionList: [],
  },
  {
    type: "input",
    inputType: "text",
    label: "电话",
    fieldName: "phone",
    placeholder: "请输入电话",
    initValue: "",
    rules: [{ max: 45, message: "不能超过45个字符", trigger: "blur" }],
  },
  {
    type: "input",
    inputType: "text",
    label: "电子邮件",
    fieldName: "email",
    placeholder: "请输入电子邮件地址",
    initValue: "",
    rules: [{ max: 45, message: "不能超过45个字符", trigger: "blur" }],
  },
  {
    type: "input", // 普通输入框
    inputType: "textarea", // 类型, text/textarea
    label: "备注", // 标签文本
    cols: "", // 自定义列
    fieldName: "remarks", // 字段名称
    placeholder: "请输入备注", // 提示文字
    initValue: "", // 默认值
    maxlength: "250", //最大输入长度 string/number
    minlength: "", // 最小输入长度 number
    showWordLimit: true, // 	是否显示统计字数, 只在 type 为 'text' 或 'textarea' 的时候生效 boolean
    rows: 3, // 输入框行数，仅 inputType 为 'textarea' 时有效 number
    autosize: {
      // 默认使用， 优先级高于rows
      minRows: 3,
      maxRows: 3,
    },
  },
];

/**
 * 全局表单参数
 */
const formConfig: any = ref(createFormConfig);
const formRef = ref();
const id = ref("");

interface partnerOption {
  value: string;
  label: string;
}

const partnerList = ref(reactive<partnerOption>([]));

function handleEchoForm(user: any) {
  let params = ["id"];
  createFormConfig.map((item) => {
    params.push(item.fieldName);
  });
  params.map((item) => {
    formRef.value.set(item, user[item]);
  });
  formRef.value.set("enabled", user["enabled"].toString());
}

/** 字典接口及数据处理 */
function getDictData(id: string) {
  return new Promise(async (resolve) => {
    const { data } = await request({
      url: `/system/Dictionary/getSelectedItems/${id}`,
      method: "post",
    });
    resolve(data);
  });
}
function handleDictData(type: string, list: any) {
  let typeIndex = 0;
  createFormConfig.map((item: any, index: number) => {
    if (item.fieldName === type) {
      typeIndex = index;
    }
  });
  createFormConfig[typeIndex].optionList = list;
}

const visibleDialog = ref(false);
watch(
  () => props.visible,
  async (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** 检测数据的变化 */
watch(
  () => props.data,
  (newVal) => {
    id.value = "";
    if (newVal.id) {
      id.value = newVal.id;
      formConfig.value = createFormConfig;
      handleEchoForm(newVal);
    } else {
      const newConfig: any[] = JSON.parse(JSON.stringify(createFormConfig));
      newConfig.splice(2, 0, ...passwordFormConfig);
      formConfig.value = newConfig;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  formConfig.value = createFormConfig;
}

async function getPartnerList() {
  return new Promise(async (resolve) => {
    const { data } = await request({
      url: "/srm/core/mdmpartner/getList",
      method: "post",
      data: {},
    });
    for (let index = 0; index < data.length; index++) {
      partnerList.value.push({
        value: data[index].id,
        label: data[index].partnerName,
      });
    }
    resolve(partnerList.value);
  });
}

const loading = ref(false);
/** 用户信息保存提交 */
function handleSubmit() {
  formRef.value.validate().then(async (res: any) => {
    loading.value = true;
    const text = id.value ? "编辑" : "新增";
    await request({
      url: "/srm/partner/user/save",
      method: "post",
      data: { ...res, id: id.value },
    }).finally(() => {
      loading.value = false;
    });
    ElMessage.success(text + `成功`);
    emit("reset-table", id.value);
    closeDialog();
  });
}

/** 初始化字典数据 */
onMounted(async () => {
  handleDictData("sexType", await getDictData("SexType"));
  handleDictData("partnerId", await getPartnerList());
  const enabledList = await getDictData("Enabled");
  handleDictData("enabled", enabledList);
  emit("get-enabled-list", enabledList);
});

// 组件销毁时调用
onBeforeUnmount(() => {
  closeDialog();
});
</script>
